package com.iszhouhua.blog.controller.vue;

import com.iszhouhua.blog.common.constant.CodeEnum;
import com.iszhouhua.blog.common.constant.Const;
import com.iszhouhua.blog.common.util.PBKDF2Utils;
import com.iszhouhua.blog.common.util.Result;
import com.iszhouhua.blog.common.util.ValidatorUtils;
import com.iszhouhua.blog.model.User;
import com.iszhouhua.blog.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 用户
 *
 * @author
 * @since
 */
@RestController
@CrossOrigin
@RequestMapping("user")
public class UserController {

  @Autowired
  private UserService userService;

  @Autowired
  private RedisTemplate redisTemplate;
  /**
   * 用户注册
   *
   * @param user
   * @return
   * @throws Exception
   */
  @PostMapping
  public Result save(@RequestBody User user) throws Exception {
    ValidatorUtils.validate(user);
    if (null != userService.findUserByUsername(user.getUsername())) {
      return  new Result(50000,"用户名已被注册", null);
    }
    if (null != userService.findUserByEmail(user.getEmail())) {
      return new Result(50000,"邮箱已被注册", null);
    }
    //生成盐
    String salt = PBKDF2Utils.getSalt();
    //加密
    String password = PBKDF2Utils.getPBKDF2(user.getPassword(), salt);
    user.setSalt(salt);
    user.setPassword(password);
    user.setLoginFailNum(0);
    user.setIsDisable(false);
    user.setIsAdmin(false);
    user.setCreateTime(new Date());
    boolean flag = userService.save(user);
    if (!flag) {
      return new Result(50000,"注册失败", null);
    }
    return new Result(20000,"注册成功", null);
  }

  /**
   * 登录
   *
   * @param user    邮箱和密码
   * @param
   * @return
   */
  @PostMapping(value = "login")
  public Result login(@RequestBody User user, HttpServletRequest request) throws Exception {
    if (StringUtils.isBlank(user.getUsername())) {
      return Result.fail("用户名不能为空");
    }
    if (StringUtils.isBlank(user.getPassword())) {
      return Result.fail("密码不能为空");
    }
    Result result = userService.login(user.getUsername(), user.getPassword());
    if (result.getCode() == CodeEnum.SUCCESS.getValue()) {

      //登录成功，将用户信息保存至session
      HttpSession session = request.getSession();
      session.setAttribute(Const.USER_SESSION_KEY + session.getId(), result.getData());
      User returnuser = (User) result.getData();
      returnuser.setPassword("");
      returnuser.setSalt("");
      redisTemplate.opsForValue().set(session.getId(),returnuser,1, TimeUnit.DAYS);
      result.setData(session.getId());
    }
    return result;
  }

  @GetMapping(value = "token")
  public Result getUserByToken(@RequestParam(value = "token") String token,
                               HttpServletRequest request){
    if (token != null){
      HttpSession session = request.getSession();
//      Object user = session.getAttribute(Const.USER_SESSION_KEY + token);
      User user = (User) redisTemplate.opsForValue().get(token);
      User userById = userService.findUserById(user.getId());
      return new Result(20000,"用户信息", userById);
    }
    return new Result(50000,"没有用户信息", null);
  }
  @PostMapping(value = "logout")
  public Result logout(HttpServletRequest request){
    String token = request.getHeader(Const.USER_SESSION_KEY);
    request.getSession().removeAttribute(Const.USER_SESSION_KEY + token);
    redisTemplate.delete(token);
    return new Result(20000,"退出成功", null);
  }
}
